package com.phf.controller.back;

import com.phf.entity.Category;
import com.phf.service.CategoryService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import javax.sound.midi.Soundbank;
import java.util.List;

@Controller
@RequestMapping("back/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @RequestMapping("show")
    public String show(@RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "6") Integer pageSize,
                       Model model){
        PageInfo<Category> pageInfo = categoryService.showCategoriesWithParent(pageNum,pageSize);
        model.addAttribute("pageInfo",pageInfo);

        return "forward:/back/category/show.jsp";
    }

    @RequestMapping("add")
    public String addCategory(Category c){
        if(c.getParentId()!=null){
            c.setLevels(2);
        }else{
            c.setLevels(1);
        }

        categoryService.addCategory(c);

        return "redirect:/back/category/show.do";
    }

    @RequestMapping("showLevel1Category")
    public String showLevel1Category(Model model){
        List<Category> categories = categoryService.showCategoriesByLevels(1);
        model.addAttribute("categories",categories);
        return "forward:/back/category/add-second.jsp";
    }

    @RequestMapping("showLevel2Category")
    public String showLevel2Category(Model model){
        List<Category> categories = categoryService.showCategoriesByLevels(2);
        model.addAttribute("categories",categories);
        return "forward:/back/book/add.jsp";
    }

    @RequestMapping("remove")
    public String removeCategory(Integer id,Integer pageNum,Integer pageSize, HttpSession session){
        try {
            categoryService.removeCategory(id);
        }catch (Exception e){
            e.printStackTrace();
            session.setAttribute("msg",e.getMessage());
        }
        return "redirect:/back/category/show.do?pageNum="+pageNum+"&pageSize="+pageSize;
    }


}
